package com.yuntian.service.Impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yuntian.Dto.AdminOrderPageQueryDto;
import com.yuntian.Dto.OrderPageQueryDto;
import com.yuntian.Vo.admin.CartVO;
import com.yuntian.Vo.admin.OrderVO;
import com.yuntian.entity.Address;
import com.yuntian.entity.Order;
import com.yuntian.entity.OrderDetail;
import com.yuntian.mapper.*;
import com.yuntian.result.PageResult;
import com.yuntian.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private AddressMapper addressMapper;

    // 查询所有订单（带详情）
    public PageResult selectAllOrder(OrderPageQueryDto orderPageQueryDto) {
        PageHelper.startPage(orderPageQueryDto.getPage(),orderPageQueryDto.getPageSize());
        Page<Order> orders = orderMapper.selectAllOrder();

        for (Order order : orders) {
            List<OrderDetail> details = orderDetailMapper.selectByOrderId(order.getOrderId());
            order.setOrderItems(details);
        }
        long total = orders.getTotal();
        List<Order> result = orders.getResult();
        return new PageResult(total,result);
    }



    // 根据用户ID查询订单
    public PageResult selectOrderByUserId(AdminOrderPageQueryDto adminOrderPageQueryDto) {
        PageHelper.startPage(adminOrderPageQueryDto.getPage(),adminOrderPageQueryDto.getPageSize());
        Long userId = adminOrderPageQueryDto.getUserId();
        Page<Order> orders = orderMapper.selectOrderByUserId(userId);
        for (Order order : orders) {
            List<OrderDetail> details = orderDetailMapper.selectByOrderId(order.getOrderId());
            order.setOrderItems(details);
        }
        long total = orders.getTotal();
        List<Order> result = orders.getResult();
        return new PageResult(total,result);

    }

    //TODO根据用户名查询订单
    public List<OrderVO> selectOrderByUserName(String userName) {
        List<OrderVO> orders = orderMapper.selectOrderByUserName(userName);
        return orders;
    }

    private void setDefaultValue(Order order) {
        LocalDateTime now = LocalDateTime.now();
        order.setCreateTime(now);
        order.setUpdateTime(now);
        order.setStatus(0);
    }

    // 创建订单
    @Transactional
    public void createOrder(Order order) {
        //查询购物车信息，提交购物车来创建订单
        if(order.getUserId() == null) {
            System.out.println("用户id为空");
        }
        List<CartVO> cartVOS = cartMapper.selectAll(order.getUserId());
        if(cartVOS == null || cartVOS.isEmpty()){
            System.out.println("购物车为空");
        }
        // 填充订单默认信息
        setDefaultValue(order);
        // 填充订单详情
        List<OrderDetail> orderDetails = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;
        for(CartVO cart : cartVOS){
            // 查询商品价格（避免用户恶意提交自己写的单价）
            BigDecimal price = productMapper.getProductPrice(cart.getProductId());
            OrderDetail detail = new OrderDetail();
            detail.setProductId(cart.getProductId());
            detail.setQuantity(cart.getQuantity());
            detail.setPrice(price);
            detail.setCreateTime(LocalDateTime.now());
            orderDetails.add(detail);
            // 累加总金额（单价*数量）
            totalAmount = totalAmount.add(price.multiply(BigDecimal.valueOf(cart.getQuantity())));
        }
        order.setTotalAmount(totalAmount);
        // 插入订单
            //插入地址
        Long userId = order.getUserId();
        Address address = addressMapper.selectAddressByUserId(userId);
        order.setAddressId(address.getAddressId());
        // 插入订单
        orderMapper.insertOrder(order);



        // 插入订单详情
        for(OrderDetail detail : orderDetails){
            detail.setOrderId(order.getOrderId());
            //
            Integer quantity = detail.getQuantity();
            Integer productId = detail.getProductId();
            Integer old = productMapper.selectProductQuantity(productId);
            if(old < quantity){
                System.out.println("库存不足");
            }
            Integer newQuantity = old - quantity;
            productMapper.updateProductPrice(newQuantity, productId);
        }
        orderDetailMapper.batchInsert(orderDetails);

        //清空购物车
        cartMapper.deleteCartByUserId(order.getUserId());
    }

    // 删除订单
    public void deleteOrder(Integer orderId) {
        orderMapper.deleteOrder(orderId);
    }


    // 订单状态更新
    public void updateOrderStatus(Order order) {


        // 设置更新时间
        order.setUpdateTime(LocalDateTime.now());

        orderMapper.updateOrderStatus(order);
    }

    // 获取订单详情
    public Order getOrderDetail(Integer orderId) {
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            System.out.println("订单不存在");
        }

        List<OrderDetail> details = orderDetailMapper.selectByOrderId(orderId);
        order.setOrderItems(details);

        return order;
    }

    @Transactional
    //确认订单信息
    public Map<String, Object> confirmOrder(Long userId) {
        if(userId == null){
            System.out.println("用户id为空");
        }
        //查询购物车信息
        List<CartVO> cartVOS = cartMapper.selectAll(userId);
        if(cartVOS == null || cartVOS.isEmpty()){
            System.out.println("购物车为空");
        }
        //返回地址信息
        Address address = addressMapper.selectAddressByUserId(userId);
        Map<String, Object> confirmData = new HashMap<>();
        confirmData.put("cartItems", cartVOS);
        confirmData.put("address", address);
        return confirmData;
    }

    /**
     * 取消订单
     * @param orderId
     */
    public void cancel(Integer orderId) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(4);
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.cancel(order);

    }

    /**
     * 统计订单数量
     * @return
     */
    @Override
    public Integer count() {
        Integer count = orderMapper.count();
        return count;
    }

}
